package com.xgd.phylw.controller;

import com.xgd.phylw.bean.Admin;
import com.xgd.phylw.bean.Member;
import com.xgd.phylw.dto.UserMessageDto;
import com.xgd.phylw.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class UserLoginRegisterController {
    @Autowired
    private UserService userService;

    @RequestMapping("memberLogin")
    public String memberLogin(Member member, @Param("code")String code, @SessionAttribute("yzm")String yzm,Model model,HttpSession session){
        System.out.println(member);
        if (code.equalsIgnoreCase(yzm)){
            int i = userService.selectMember(member);
            if(i==1){
                session.setAttribute("user",userService.queryMember(member));
                System.out.println("登录成功！");
                return "redirect:index.jsp";
            }else if(i==-1){
                model.addAttribute("msg","亲，您的密码错啦！");
            }else if(i==0){
                model.addAttribute("msg","亲，用户不存在哦~");
            }else{
                model.addAttribute("msg","用户名重复太多，换一个吧~");
            }
        }
        System.out.println("Controller:"+yzm);
        return "redirect:login.jsp";
    }
    @RequestMapping("memberNo")
    public String memberNo(HttpSession session){
        session.setAttribute("user",null);
        return "redirect:login.jsp";
    }
    @RequestMapping("adminNo")
    public String adminNo(HttpSession session){
        session.setAttribute("user",null);
        return "redirect:adm_login.jsp";
    }
    @RequestMapping("adminLogin")
    public String adminLogin(Admin admin,Model model,HttpSession session){
        int i = userService.selectAdmin(admin);
        System.out.println(i);
        if(i==1){
            session.setAttribute("user",userService.queryAdmin(admin));
            System.out.println("admin登录成功！");
            return "admin_index";
        }else if(i==-1){
            model.addAttribute("msg","亲，您的密码错啦！");
        }else if(i==0){
            model.addAttribute("msg","亲，用户不存在哦~");
        }else{
            model.addAttribute("msg","用户名重复太多，换一个吧~");
        }
        return "redirect:adm_login.jsp";
    }

    @RequestMapping("/memberRegister")
    public String memberRegister(@Valid Member member, BindingResult bindingResult, String password, Model model
            , @RequestParam(required = false)MultipartFile img,HttpSession session) throws IOException {

        if (bindingResult.hasErrors()){//校验有误
            Map<String,Object> map = new HashMap<String, Object>();
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError:fieldErrors){
                map.put(fieldError.getField(),fieldError.getDefaultMessage());
                System.out.println(map);
            }
            model.addAttribute("error",map);
        }else{
            if(password.equals(member.getMemberPass())){
                if(img.isEmpty()){
                    System.out.println("默认头像");
                    member.setMemberHead("images/head/default.jpg");

                    int i = userService.insertMember(member);
                    if(i==1){
                        session.setAttribute("user",userService.queryMember(member));
                        System.out.println("注册成功！");
                        return "redirect:index.jsp";
                    }
                }else{
                    System.out.println("图像区域：");

                    String realPath =  session.getServletContext().getRealPath("");
                    realPath +="/images/head/";
                    String headPath = "images/head/"+img.getOriginalFilename();
                    File file = new File(realPath + img.getOriginalFilename());
                    member.setMemberHead(headPath);

                    int i = userService.insertMember(member);
                    if(i==1){
                        session.setAttribute("user",userService.queryMember(member));
                        img.transferTo(file);
                        System.out.println("注册成功！");
                        return "redirect:index.jsp";
                    }
                }
            }else{
                model.addAttribute("msg","亲，两次密码不一致哦~");
            }

        }
        return "redirect:register.jsp";
    }
    @RequestMapping("ADMmemberRegister")
    public String ADMmemberRegister(@Valid Member member, BindingResult bindingResult,Model model) throws IOException {
        System.out.println(member);
        if (bindingResult.hasErrors()){//校验有误
            Map<String,Object> map = new HashMap<String, Object>();
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError:fieldErrors){
                System.out.println(fieldError.getField());
                map.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            model.addAttribute("error",map);
        }else{
            member.setMemberHead("images/head/default.jpg");
            System.out.println(member);
            int i = userService.insertMember(member);
            if(i==1){
                System.out.println("注册成功！");
                return "redirect:Users";
            }

        }
        return "users_add";
    }



//    聊天信息
    @RequestMapping("sendUserMessage")
    @ResponseBody
    protected List<UserMessageDto> sendUserMessage(String message,@SessionAttribute("user")Member name,Model model){
        System.out.println(name);
        List<UserMessageDto> list =new ArrayList<UserMessageDto>();
        if(list == null) {
            list = new ArrayList();
        }
        if(message != null) {
            UserMessageDto messageDto = new UserMessageDto();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH-mm-ss");

            messageDto.setMessage(message);
            messageDto.setMyimg(name.getMemberHead());
            messageDto.setName(name.getMemberName());
            messageDto.setMytime(sdf.format(Calendar.getInstance().getTime()));
            list.add(messageDto);
        }
        model.addAttribute("userMessage",null);
        return list;
    }
}
